package com.ruoyi.company.utils.pdf;

import com.lowagie.text.pdf.BaseFont;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

/**
 * @author WangChangShuo
 * @date 2022年06月23日 16:51
 */
public class HtmlToPdf {
    /**
     * 通过html的字符串转pdf
     * @param out
     * @param html
     * @throws IOException
     */
    public static void createPdfByHtml(OutputStream out, String html) {
        try {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文支持问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            //字符集
            URL resource = HtmlToPdf.class.getClassLoader().getResource("static/fonts/simsun.ttc");

            fontResolver.addFont(resource.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过html的文件路径转pdf
     * @param out
     * @param htmlFilePath
     * @throws IOException
     * @throws
     */
    public static void createPdfByUrl(OutputStream out,String htmlFilePath) {
        try {
            ITextRenderer renderer = new ITextRenderer();
            String url = new File(htmlFilePath).toURI().toURL().toString();
            renderer.setDocument(url);
            // 解决中文支持问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            String fontPath = ResourceUtils.getURL("/ajax/libs/summernote/font/simsun.ttc").getPath();
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //解决图片的相对路径问题
            //renderer.getSharedContext().setBaseURL("http://localhost:8080");//file:/e:/
            renderer.layout();
            renderer.createPDF(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
